import os,sys
import random
import piexif
import pickle
from tkinter import filedialog, messagebox, simpledialog
from PIL import Image, ImageEnhance
from datetime import datetime, timedelta





# **加载 EXIF 数据**
def load_exif_data():
    if getattr(sys, 'frozen', False):
        BASE_DIR = sys._MEIPASS  # PyInstaller 运行时的临时目录
    else:
        BASE_DIR = os.path.dirname(os.path.abspath(__file__))  # 脚本运行目录

    # EXIF 数据存储文件路径
    exif_data_file = os.path.join(BASE_DIR, "exif_data.pkl")
    if not os.path.exists(exif_data_file):
        messagebox.showerror("错误", "未找到 EXIF 数据文件，请先提取 EXIF！")
        return None

    with open(exif_data_file, "rb") as f:
        return pickle.load(f)
#
def process_image(image_path):
    # 获取文件扩展名
    file_ext = os.path.splitext(image_path)[-1].lower()
    
    # 打开图片
    image = Image.open(image_path)

    # 如果不是 JPG 格式，转换为 JPG 并删除原文件
    if file_ext not in ['.jpg', '.jpeg']:
        new_path = image_path.rsplit('.', 1)[0] + '.jpg'
        image.convert('RGB').save(new_path, 'JPEG')
        os.remove(image_path)  # 删除原始文件
        image_path = new_path
        image = Image.open(image_path)

    # 降低饱和度
    enhancer = ImageEnhance.Color(image)
    image = enhancer.enhance(0.9)  # 0.5 表示降低饱和度

    # 调整图片宽度为 3200px，高度等比缩放
    width, height = image.size
    new_height = int(3200 * height / width)
    image = image.resize((3200, new_height), Image.LANCZOS)

    # 确保文件大小 ≥ 1023KB
    quality = 95  # 初始 JPEG 质量
    temp_path = "temp.jpg"
    while True:
        image.save(temp_path, "JPEG", quality=quality)
        if os.path.getsize(temp_path) >= 1023 * 1024 or quality <= 10:
            break
        quality -= 5  # 逐步降低质量以增大文件大小

    # 保存最终图片并删除临时文件
    image.save(image_path, "JPEG", quality=quality)
    os.remove(temp_path)

    print(f"处理完成: {image_path}")
# **随机生成上个月的某一天的拍摄时间（9:00 - 18:00）**
def get_random_datetime():
    today = datetime.today()
    first_day_last_month = today.replace(day=1) - timedelta(days=1)
    last_month = first_day_last_month.month
    year = first_day_last_month.year

    # **随机选择上个月的某一天**
    day = random.randint(1, first_day_last_month.day)
    hour = random.randint(9, 18)  # **9:00 - 18:00**
    minute = random.randint(0, 59)
    second = random.randint(0, 59)

    return f"{year}:{last_month:02d}:{day:02d} {hour:02d}:{minute:02d}:{second:02d}"

# **批量给文件夹内所有 JPG 添加 EXIF**
def apply_exif_to_folder(folder_selected):
    if not folder_selected:
        return

    exif_data = load_exif_data()
    if not exif_data:
        return

    pic_files = [f for f in os.listdir(folder_selected) if f.lower().endswith(".jpg")]+[f for f in os.listdir(folder_selected) if f.lower().endswith(".png")]
    if not pic_files:
        messagebox.showinfo("提示", "文件夹内没有 JPG&PNG 图片")
        return
    # **开始添加 EXIF**
    for filename in pic_files:
        file_path = os.path.join(folder_selected, filename)
        process_image(file_path)

    pic_files = [f for f in os.listdir(folder_selected) if f.lower().endswith(".jpg")]
    # **开始添加 EXIF**
    for filename in pic_files:
        file_path = os.path.join(folder_selected, filename)
        random_exif = random.choice(list(exif_data.values()))  # **随机选取 EXIF**

        # **修改拍摄时间**
        new_datetime = get_random_datetime()
        if "Exif" in random_exif:
            random_exif["Exif"][piexif.ExifIFD.DateTimeOriginal] = new_datetime.encode()
            random_exif["Exif"][piexif.ExifIFD.DateTimeDigitized] = new_datetime.encode()

        try:
            exif_bytes = piexif.dump(random_exif)
            piexif.insert(exif_bytes, file_path)
            print(f"✅ {filename} 添加 EXIF，拍摄时间改为 {new_datetime}")
        except Exception as e:
            print(f"❌ 处理 {filename} 失败，错误：{e}")

    messagebox.showinfo("完成", f"已为 {len(pic_files)} 张图片添加 EXIF！")